import 'package:flutter/cupertino.dart';
import 'package:flutter_scaffold/flutter_scaffold.dart';

/// 假如有3个页面，分别是A、B、C，跳转逻辑由A->B->C，而RouteAware使用with混淆在B中。
/// didPopNext：在C页面关闭后，B页面调起该方法；
/// didPush: 当由A打开B页面时，B页面调起该方法；
/// didPop: 当B页面关闭时，B页面调起该方法；
/// didPushNext: 当从B页面打开C页面时，该方法被调起。
/// @author zhibo.huang
/// @date   2025/6/16
abstract class ViewModelWidgetState<VM extends BaseViewModel, W extends StatefulWidget> extends State<W>
    with RouteAware {
  final RouteObserver<Route> routeObserver = RouteObserverUtil().routeObserver;

  late VM viewModel;

  @override
  void initState() {
    super.initState();
    viewModel = Get.put<VM>(createViewModel(), tag: viewModelTag(), permanent: isPermanent());
    WidgetsBinding.instance.addPostFrameCallback((_) {
      onReady();
    });
  }

  void onReady();

  VM createViewModel();

  String? viewModelTag() {
    //此处决定同一个viewModel是否共用一个.默认情况是独立实例化
    //比如多个页面,同一个ViewModel类型,会存在多个实例化
    if (widget.key != null) {
      return '${runtimeType.toString()}_${widget.key.toString()}';
    }
    return '${runtimeType.toString()}_$hashCode';
  }

  bool isPermanent() {
    return false;
  }

  Widget buildWidget(BuildContext context, VM viewModel);

  @override
  Widget build(BuildContext context) {
    return buildWidget(context, viewModel);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final route = ModalRoute.of(context);
    if (route != null) {
      routeObserver.subscribe(this, route);
    }
  }

  @override
  void didPopNext() {
    super.didPopNext();
    Get.find<VM>(tag: viewModelTag()).onResumed();
  }

  @override
  void didPushNext() {
    super.didPushNext();
    Get.find<VM>(tag: viewModelTag()).onPaused();
  }

  @override
  void dispose() {
    super.dispose();
    routeObserver.unsubscribe(this);
    Get.delete<VM>(tag: viewModelTag(), force: false);
  }
}
